import request from "./request";

export function exportExecl(fileName, url, params, obj, type = ".xlsx") {
  const loading = obj.$loading({
    lock: true,
    text: "生成中",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  fileName = fileName || "导出信息";
  fileName = fileName + type;
  request({
    url,
    method: "get",
    params,
    responseType: "blob",
    timeout: 600000,
  })
    .then((data) => {
      loading.close();
      const blob = new Blob([data]);
      if ("download" in document.createElement("a")) {
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    })
    .catch((error) => {
      loading.close();
      var reader = new FileReader();
      reader.readAsText(error.response.data, "utf-8");
      reader.onload = function (e) {
        const res = JSON.parse(e.target.result);
        obj.$message.error(res.message, 5 * 1000);
      };
    });
}
